package com.atguigu.tingshu.user.config;

import cn.binarywang.wx.miniapp.api.WxMaService;
import cn.binarywang.wx.miniapp.api.impl.WxMaServiceImpl;
import cn.binarywang.wx.miniapp.config.impl.WxMaDefaultConfigImpl;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.ClassPathResource;
import org.springframework.security.jwt.crypto.sign.RsaSigner;
import org.springframework.security.jwt.crypto.sign.Signer;
import org.springframework.security.rsa.crypto.KeyStoreKeyFactory;
import java.security.KeyPair;
import java.security.interfaces.RSAPrivateKey;

@EnableConfigurationProperties(WxProperties.class)
@Configuration
public class WxAutoConfiguration {
    //微信自动配置类型
    @Bean
    public WxMaService wxMaService(WxProperties wxProperties) {
        //定义一个WxMaService的实现类对象
        WxMaServiceImpl wxMaService = new WxMaServiceImpl();
        //给WxMaServiceImpl对象属性赋值
        WxMaDefaultConfigImpl wxMaDefaultConfig = new WxMaDefaultConfigImpl();
        wxMaDefaultConfig.setAppid(wxProperties.getAppId());
        wxMaDefaultConfig.setSecret(wxProperties.getAppSecret());
        wxMaService.setWxMaConfig(wxMaDefaultConfig);
        return wxMaService;
    }
    @Bean
    public Signer rsaSigner() {
        //获取thingshu.jks证书
        ClassPathResource resource = new ClassPathResource("tingshu.jks");
        //获得钥匙工厂对象
        KeyStoreKeyFactory keyFactory = new KeyStoreKeyFactory(resource, "tingshu".toCharArray());
        //获取钥匙对
        KeyPair keyPair = keyFactory.getKeyPair("tingshu", "tingshu".toCharArray());
        //获取私钥(强转),加签
        RSAPrivateKey key = (RSAPrivateKey) keyPair.getPrivate();
        return new RsaSigner(key);
    }
}
